package gaubee.BLL;

import gaubee.model.BaseHibernateDAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Transaction;

import net.sf.json.*;

public class BaseBLL implements Servlet{

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}


	private BaseHibernateDAO basehibernateDAO = new BaseHibernateDAO();
	
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		res.setContentType("application/json");
		Transaction transaction = basehibernateDAO.getSession().beginTransaction();
		res.setCharacterEncoding("UTF-8");
		run(req,res);
		transaction.commit();
		basehibernateDAO.getSession().close();
	}
	
	public void run(ServletRequest req, ServletResponse res) throws IOException{
		
	}
	
	public String writeJSONstringify(Object result,PrintWriter pw){
		String jsonString;
		JSONObject jsonResult = JSONObject.fromObject(result);
		jsonString = jsonResult.toString();
		if (pw!=null) {
			pw.println(jsonString);
		}
		return jsonString;
	}

	public Map simpleResult(Object result,String method,String status){
		Map mapResult = new HashMap();
		mapResult.put("result",result);
		mapResult.put("method",method);
		mapResult.put("message",status);
		return mapResult;
	}

	public String writeJSONstringify(List result,PrintWriter pw){
		String jsonString;
		JSONArray jsonResult = JSONArray.fromObject(result);
		jsonString = jsonResult.toString();
		if (pw!=null) {
			pw.println(jsonString);
		}
		return jsonString;
	}

	public static Timestamp StringToTimestamp(String timeStr){
		Timestamp result = null;
		Date date = null;
		try{
			date = new Date(Long.parseLong(timeStr));
		}catch(Exception e){
			date = new Date();
		}
		result = new Timestamp(date.getTime());
		return result;
	}
}
